<template>
  <div>
    <el-dialog :model-value="visible" :close-on-click-modal="false" title="新增账号" width="500" @close="cls">
      <!--表单-->
      <el-form ref="ruleFormRef" style="max-width: 400px" :model="ruleForm" label-width="100px" status-icon>
        <el-form-item label="账号编号">
          <el-input v-model="ruleForm.code" placeholder="该编号自动生成,无需手动添加" :disabled="true"/>
        </el-form-item>
        <el-form-item label="账号名称">
          <el-input v-model="ruleForm.name" placeholder="请输入账号编号" />
        </el-form-item>
        <el-form-item label="账户余额">
          <el-input v-model="ruleForm.nowMoney" placeholder="请输入账户余额" />
        </el-form-item>
        <el-form-item label="账户列表">
          <el-select v-model="ruleForm.type" clearable placeholder="现金">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saves">保存</el-button>
          <el-button @click="cls">不保存关闭</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script setup>
import { ref } from 'vue';
import { ElMessage } from "element-plus";
import { save, update } from "@/api/account/account.js";
//声明属性
const props = defineProps({
  "visible": {
    type: Boolean,
    default: false
  }
})
//声明事件
const emits = defineEmits(["close", "refresh"])
//表明引用，要求响应对象与表单属性ref的值保持一致
const ruleFormRef = ref(null)
//表单数据
const ruleForm = ref({
  name: "",
  nowMoney: "",
  type: "",
  code: ""
})

const statusOptions = [
  {
    value: '1',
    label: '现金',
  },
  {
    value: '2',
    label: '银行卡',
  }]


//保存
async function saves() {
  //调用表单校验 异步的
  let valid = await ruleFormRef.value.validate(valid => {
  });
  if (!valid)
    return;
  let res;
  //判断当前是修改还是保存
  if (ruleForm.value.id) {
    //修改
    res = await update(ruleForm.value)
  } else {
    res = await save(ruleForm.value);
  }
  //验证通过，提交表单
  //等待接口返回数据以后再继续执行
  if (res.code == 200) {
    ElMessage({
      message: '保存成功',
      type: 'success'
    })
    //关闭窗口
    cls();
    //通知父窗口刷新数据
    emits("refresh");
  }
}

//组件显示时调用的初始化方法
function init(data) {
  if (data) {
    //说明是修改
    ruleForm.value = data;
  } else {
    ruleForm.value = {
      name: "",
      nowMoney: "",
      type: "",
      code: ""
    }
  }
}
//暴露
defineExpose({ init })

//关闭窗口
function cls() {
  //抛出自定义事件
  emits("close");
}
</script>